// 统一的API请求服务
import { message } from 'antd';
import { API_BASE_URL } from '@/config';


// 通用响应接口
export interface ApiResponse<T = any> {
  code: string;
  flag: string;
  msg: string;
  data: T;
}

// 请求配置接口
export interface RequestConfig {
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  headers?: Record<string, string>;
  body?: any;
  requireAuth?: boolean;
}

// 获取用户认证信息
function getAuthInfo() {
  const auth_token = localStorage.getItem('auth_token');
  if (!auth_token) {
    return { auth_token: '', user: null };
  }
  
  try {
    return {
      auth_token: auth_token,
    };
  } catch (error) {
    console.error('解析用户数据失败:', error);
    return { auth_token: '', user: null };
  }
}

// 统一的请求方法
export async function apiRequest<T = any>(
  url: string,
  config: RequestConfig = {}
): Promise<ApiResponse<T>> {
  const {
    method = 'GET',
    headers = {},
    body,
    requireAuth = true
  } = config;

  // 构建请求头
  const requestHeaders: Record<string, string> = {
    'Content-Type': 'application/json',
    ...headers
  };

  // 添加认证头
  if (requireAuth) {
    const { auth_token } = getAuthInfo();
    if (auth_token) {
      requestHeaders['Authorization'] = `Bearer ${auth_token}`;
    }
  }

  // 构建请求配置
  const requestConfig: RequestInit = {
    method,
    headers: requestHeaders,
  };

  // 添加请求体
  if (body && method !== 'GET') {
    requestConfig.body = typeof body === 'string' ? body : JSON.stringify(body);
  }

  try {
    const response = await fetch(url, requestConfig);
    const data = await response.json();
    
    if (!response.ok) {
      throw new Error(data.msg || `HTTP error! status: ${response.status}`);
    }
    
    return data;
  } catch (error) {
    console.error('API请求失败:', error);
    throw error;
  }
}

// 带错误处理的API请求方法
export async function apiRequestWithErrorHandling<T = any>(
  url: string,
  config: RequestConfig = {},
  options: {
    successMessage?: string;
    errorMessage?: string;
    showSuccessMessage?: boolean;
    showErrorMessage?: boolean;
  } = {}
): Promise<ApiResponse<T> | null> {
  const {
    successMessage,
    errorMessage = '操作失败',
    showSuccessMessage = false,
    showErrorMessage = true
  } = options;

  try {
    const result = await apiRequest<T>(url, config);
    
    if (showSuccessMessage && successMessage) {
      message.success(successMessage);
    }
    
    return result;
  } catch (error) {
    if (showErrorMessage) {
      const errorMsg = error instanceof Error ? error.message : errorMessage;
      message.error(errorMsg);
    }
    
    console.error('API请求错误:', error);
    return null;
  }
}

// 上传文件信息请求接口
export interface UploadFileInfoRequest {
  url: string;
  outUrl: string;
  mediaType: number;
  type: string;
  size: number;
  lastModified: number;
  width: number;
  height: number;
  agId: string;
  postId: string;
  groud_id: string;
  isWeiBo?: string;
}

export interface Media {
  id: string;
  url: string;
  type: string;
  size: number;
  width: number;
  height: number;
  outUrl?: string;
}

export interface UploadFileInfoResponse {
  code: number;
  data: Media;
  msg: string;
}

// OSS上传签名响应接口
export interface OssUploadSignatureResponse {
  policy: string;
  signature: string;
  x_oss_credential: string;
  x_oss_date: string;
  security_token: string;
  host: string;
  dir: string;
}

// API服务对象
export const apiService = {
  // 获取OSS上传签名
  async getOssUploadSignature(): Promise<OssUploadSignatureResponse | null> {
    const { auth_token } = getAuthInfo();
    if (!auth_token) {
      throw new Error('用户未登录');
    }
    try {
      // 注意：根据API文档，这里应该是获取OSS上传签名的接口
      // 如果后端没有提供专门的签名接口，可能需要调整实现方式
      const response = await fetch(`${API_BASE_URL}/api/v1/oss/get_post_signature_for_oss_upload`, { 
        method: 'GET' ,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${auth_token}`,
        },
      });
      
      if (!response.ok) {
        throw new Error('获取签名失败');
      }
      
      const data = await response.json();
          console.log("oss upload config", data.data)

      const ossData: OssUploadSignatureResponse = data.data;
      if (ossData.dir == null) {
        return null;
      }
      return ossData;
    } catch (error) {
      console.error('获取OSS签名失败:', error);
      return null;
    }
  },

  // OSS文件上传（带进度监控）
  async uploadFileToOss(
    file: File, 
    ossConfig: OssUploadSignatureResponse,
    onProgress?: (progress: number) => void
  ): Promise<string | null> {
    return new Promise((resolve, reject) => {
      try {
        const formData = new FormData();
        const cleanedFileName = Date.now() + file.name;
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const fileName = ossConfig.dir + `images/${year}/${month}/${day}/${cleanedFileName}`;
        
        formData.append('success_action_status', '200');
        formData.append('policy', ossConfig.policy);
        formData.append('x-oss-signature', ossConfig.signature);
        formData.append('x-oss-signature-version', 'OSS4-HMAC-SHA256');
        formData.append('x-oss-credential', ossConfig.x_oss_credential);
        formData.append('x-oss-date', ossConfig.x_oss_date);
        formData.append('cache-control', 'max-age=2592000');
        formData.append('Expires', 'Thu, 31 Dec 2099 23:59:59 GMT');
        formData.append('x-oss-meta-no-last-modified', 'true');
        formData.append('key', fileName);
        formData.append('x-oss-security-token', ossConfig.security_token);
        formData.append('file', file); // file 必须为最后一个表单域
  
        const xhr = new XMLHttpRequest();
        
        // 上传进度监听
        xhr.upload.addEventListener('progress', (event) => {
          if (event.lengthComputable && onProgress) {
            const progress = Math.round((event.loaded / event.total) * 100);
            onProgress(progress);
          }
        });
        
        // 上传完成监听
        xhr.addEventListener('load', () => {
          if (xhr.status >= 200 && xhr.status < 300) {
            console.log('上传成功', xhr.response);
            resolve(fileName);
          } else {
            console.log('上传失败', xhr.response);
            resolve(null);
          }
        });
        
        // 上传错误监听
        xhr.addEventListener('error', () => {
          console.error('OSS上传发生错误:', xhr.statusText);
          resolve(null);
        });
        
        // 上传中止监听
        xhr.addEventListener('abort', () => {
          console.log('上传被中止');
          resolve(null);
        });
        
        xhr.open('POST', ossConfig.host);
        xhr.send(formData);
        
      } catch (error) {
        console.error('OSS上传发生错误:', error);
        resolve(null);
      }
    });
  },

  // 上传文件信息（根据API文档，这个接口可能需要调整）
  async uploadFileInfo(data: UploadFileInfoRequest): Promise<UploadFileInfoResponse | null> {
    try {
      const { auth_token } = getAuthInfo();
      if (!auth_token) {
        throw new Error('用户未登录');
      }

      // 注意：API文档中没有明确的uploadFileInfo接口
      // 这里暂时保持原有逻辑，可能需要根据实际后端接口调整
      const response = await fetch(`${API_BASE_URL}/api/v1/upload/image`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${auth_token}`,
        },
        body: JSON.stringify(data)
      });

      console.log('上传成功', response);
      
      if (response.ok) {
        const result: UploadFileInfoResponse = await response.json();
        console.log('上传信息成功', result);
        return result;
      } else {
        console.log('上传信息失败', response);
        return null;
      }
    } catch (error) {
      console.error('发生信息错误:', error);
      return null;
    }
  },
};

export default apiService;
